'use strict'

let models = require('../modules/models');
let Fiber = require('fibers');

let Role = models.Role;
let Privilege = models.Privilege;

let RoleDao = models.RoleDao;
let PrivilegeDao = models.PrivilegeDao;

let privilegeData = {
    'student': {},
    'teacher': {},
    'leader': {}
};

Fiber(function() {
    syncPrivileges();
    syncRoles();
    
    process.exit();
}).run();

let roleData = {
    student: {
        privileges: [ 
            'student'
        ]
    },
    teacher: {
        privileges: [
            'teacher'
        ]
    },
    leader: {
        privileges: [
            'leader'
        ]
    },
    leaderTeacher: {
        privileges: [
            'leader',
            'teacher'
        ]
    }
};

let privileges = {};
let roles = {};

function syncPrivileges() {
    Object.keys(privilegeData).forEach(privilegeName => {
        let privilege = PrivilegeDao.findOne({
            name: privilegeName
        });

        if ( !privilege ) {
            privilege = new Privilege({
                name: privilegeName
            });
            PrivilegeDao.create(privilege);
        }

        privileges[privilegeName] = privilege;
    });
}

function syncRoles() {
    Object.keys(roleData).forEach(roleName => {
        let roleDatum = roleData[roleName];

        let role = RoleDao.findOne({
            name: roleName
        });

        if ( !role ) {
            role = new Role({
                name: roleName
            });
            RoleDao.create(role);
        }

        role.privileges = roleDatum.privileges.map(privilegeName => {
            return privileges[privilegeName];
        });

        RoleDao.update(role);
    });
}
